import pygame
import random
import sys
import os
import platform

pygame.init()

# ---------- 自动检测系统并加载中文字体 ----------
def get_chinese_font():
    sys_name = platform.system()
    if sys_name == "Windows":
        font_path = r"C:\Windows\Fonts\msyh.ttc"  # 微软雅黑
    elif sys_name == "Darwin":  # macOS
        font_path = "/System/Library/Fonts/STHeiti Light.ttc"
    else:  # Linux
        # 这里可以改成你系统中常见的中文字体路径
        font_path = "/usr/share/fonts/truetype/arphic/ukai.ttc"
    
    if not os.path.exists(font_path):
        print("⚠️ 找不到系统中文字体，使用默认字体，可能会出现方块。")
        font_path = pygame.font.get_default_font()
    return font_path

FONT_PATH = get_chinese_font()

# ---------- 游戏配置 ----------
WIDTH, HEIGHT = 600, 400
CELL_SIZE = 20
SPEED = 8  # 降低速度更舒适

# ---------- 颜色 ----------
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
BLUE = (0, 128, 255)

# ---------- 初始化窗口 ----------
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("🐍 贪吃蛇 AI 游戏")

# ---------- 字体 ----------
font_big = pygame.font.Font(FONT_PATH, 48)
font_mid = pygame.font.Font(FONT_PATH, 32)
font_small = pygame.font.Font(FONT_PATH, 24)

clock = pygame.time.Clock()

# ---------- 绘制文字 ----------
def draw_text(text, font, color, x, y, center=True):
    text_surface = font.render(text, True, color)
    text_rect = text_surface.get_rect()
    if center:
        text_rect.center = (x, y)
    else:
        text_rect.topleft = (x, y)
    screen.blit(text_surface, text_rect)

# ---------- 游戏主逻辑 ----------
def game_loop(is_ai=False):
    snake = [(100, 100), (80, 100), (60, 100)]
    direction = "RIGHT"
    food = (random.randrange(1, WIDTH // CELL_SIZE) * CELL_SIZE,
            random.randrange(1, HEIGHT // CELL_SIZE) * CELL_SIZE)
    score = 0
    running = True

    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                if not is_ai:
                    if event.key == pygame.K_UP and direction != "DOWN":
                        direction = "UP"
                    elif event.key == pygame.K_DOWN and direction != "UP":
                        direction = "DOWN"
                    elif event.key == pygame.K_LEFT and direction != "RIGHT":
                        direction = "LEFT"
                    elif event.key == pygame.K_RIGHT and direction != "LEFT":
                        direction = "RIGHT"

        # ---------- AI 控制 ----------
        if is_ai:
            head_x, head_y = snake[0]
            fx, fy = food
            if fx > head_x:
                direction = "RIGHT"
            elif fx < head_x:
                direction = "LEFT"
            elif fy > head_y:
                direction = "DOWN"
            elif fy < head_y:
                direction = "UP"

        # ---------- 蛇移动 ----------
        x, y = snake[0]
        if direction == "UP":
            y -= CELL_SIZE
        elif direction == "DOWN":
            y += CELL_SIZE
        elif direction == "LEFT":
            x -= CELL_SIZE
        elif direction == "RIGHT":
            x += CELL_SIZE
        new_head = (x, y)

        # ---------- 撞墙或自撞 ----------
        if (x < 0 or x >= WIDTH or y < 0 or y >= HEIGHT or new_head in snake):
            game_over(score)
            return

        snake.insert(0, new_head)

        # ---------- 吃食物 ----------
        if new_head == food:
            score += 1
            food = (random.randrange(1, WIDTH // CELL_SIZE) * CELL_SIZE,
                    random.randrange(1, HEIGHT // CELL_SIZE) * CELL_SIZE)
        else:
            snake.pop()

        # ---------- 绘制 ----------
        screen.fill(BLACK)
        for s in snake:
            pygame.draw.rect(screen, GREEN, (*s, CELL_SIZE, CELL_SIZE))
        pygame.draw.rect(screen, RED, (*food, CELL_SIZE, CELL_SIZE))
        draw_text(f"得分：{score}", font_small, WHITE, 50, 20, center=False)
        pygame.display.flip()
        clock.tick(SPEED)

# ---------- 游戏结束 ----------
def game_over(score):
    screen.fill(BLACK)
    draw_text("游戏结束", font_big, RED, WIDTH // 2, HEIGHT // 3)
    draw_text(f"得分：{score}", font_mid, WHITE, WIDTH // 2, HEIGHT // 2)
    draw_text("按 Enter 返回菜单", font_small, BLUE, WIDTH // 2, HEIGHT * 2 // 3)
    pygame.display.flip()

    waiting = True
    while waiting:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            if event.type == pygame.KEYDOWN and event.key == pygame.K_RETURN:
                waiting = False

# ---------- 菜单 ----------
def main_menu():
    while True:
        screen.fill(BLACK)
        draw_text("🐍 贪吃蛇 AI 游戏", font_big, GREEN, WIDTH // 2, HEIGHT // 4)
        draw_text("1. 开始游戏（玩家模式）", font_mid, WHITE, WIDTH // 2, HEIGHT // 2)
        draw_text("2. 开始游戏（AI 模式）", font_mid, WHITE, WIDTH // 2, HEIGHT // 2 + 50)
        draw_text("ESC. 退出", font_small, RED, WIDTH // 2, HEIGHT - 60)
        pygame.display.flip()

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_1:
                    game_loop(is_ai=False)
                elif event.key == pygame.K_2:
                    game_loop(is_ai=True)
                elif event.key == pygame.K_ESCAPE:
                    pygame.quit()
                    sys.exit()

if __name__ == "__main__":
    main_menu()
